import dayjs from 'dayjs';
import { readBody } from 'h3';
import { SiteModel } from '~/server/models/site.model';

// 更新站点配置，isUse 互斥
export default defineEventHandler(async (event): Promise<any> => {
	try {
		const body = await readBody(event);

		const { _id, title, description, keywords, globalCss, globalJs, isUse } = body;

		if (!_id) {
			return { code: 0, message: '缺少 _id' };
		}

		if (isUse) {
			// 如果本次设置 isUse 为 true，其他全部设为 false
			await SiteModel.updateMany({ isUse: true }, { isUse: false });
		}

		await SiteModel.findByIdAndUpdate(_id, {
			title,
			description,
			keywords,
			globalCss,
			globalJs,
			isUse,
			updatedAt: dayjs().format('YYYY年MM月DD日 HH:mm:ss'),
		});

		return { code: 1, message: '更新成功' };
	} catch (error: any) {
		return { code: 0, message: error.message };
	}
});
